//
//  MyPraiseViewController.m
//  yunyan
//
//  Created by haichuang on 2018/3/14.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "MyPraiseViewController.h"
#import "LikeOneImageTableViewCell.h"
#import "NewsDetailsViewController.h"
#import "ActiveDetailViewController.h"
@interface MyPraiseViewController ()<UITableViewDataSource , UITableViewDelegate>
{
    BOOL _isEditing;  // 判断UITableView是否处于编辑状态
    NSArray * _dataArray;
}

@property (nonatomic, strong) UITableView * praiseTab;
@property (nonatomic, strong)UIButton *deleteBtn;
@end

@implementation MyPraiseViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    WeakSelf;
   
    
    [self customNaviItemTitle:@"我的点赞" isLeft:YES];
//     [self customTabBarButtonTitle:@"编辑" image:nil target:self action:@selector(rightButtonEvent) isLeft:NO];
    self.praiseTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.view addSubview:_praiseTab];
   
 
    [_praiseTab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo (weakSelf.view);
       
    }];
    
    self.praiseTab.delegate = self;
    self.praiseTab.dataSource = self;
 
   [self.praiseTab registerNib:[UINib nibWithNibName:@"LikeOneImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"LikeOneImageTableViewCell"];
    
    _deleteBtn = [[UIButton alloc] init];
    [self.view addSubview:_deleteBtn];
    [_deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.equalTo (weakSelf.view);
        make.height.equalTo (@(50.0f));
        
    }];
    [_deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    _deleteBtn.titleLabel.font = [UIFont systemFontOfSize:18.f];
    _deleteBtn.backgroundColor = RGBA(81, 158, 238, 1);
    _deleteBtn.hidden = YES;
    [_deleteBtn addTarget:self action:@selector(onDeleteBtn) forControlEvents:UIControlEventTouchUpInside];
    
    [self getLikeListRequest];
}

//
//-(void)rightButtonEvent{
//    WeakSelf;
//    if (_isEditing) {
//        // 当退出编辑时
//        self.praiseTab.allowsMultipleSelectionDuringEditing = NO;
//        // 取消编辑模式
//        [self.praiseTab setEditing:NO animated:YES];
//
//        [_praiseTab mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.bottom.equalTo (weakSelf.view.mas_bottom);
//;
//
//        }];
//        [_deleteBtn mas_updateConstraints:^(MASConstraintMaker *make) {
//
//            make.left.right.bottom.equalTo (weakSelf.view);
//            make.height.equalTo (@(0.0f));
//
//        }];
//        [self customTabBarButtonTitle:@"编辑" image:nil target:self action:@selector(rightButtonEvent) isLeft:NO];
//        _deleteBtn.hidden = YES;
//        _isEditing = NO;
//    }
//    else
//    {
//        self.praiseTab.allowsMultipleSelectionDuringEditing = YES;
//
//        [self.praiseTab setEditing:YES animated:YES];
//        [_praiseTab mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.bottom.equalTo (weakSelf.view.mas_bottom).offset (-50.f);
//            ;
//
//        }];
//        [_deleteBtn mas_updateConstraints:^(MASConstraintMaker *make) {
//
//            make.left.right.bottom.equalTo (weakSelf.view);
//            make.height.equalTo (@(50.0f));
//
//        }];
////        [_praiseTab mas_updateConstraints:^(MASConstraintMaker *make) {
////            make.left.right.bottom.top.equalTo (weakSelf.view);
////
////        }];
//        [self customTabBarButtonTitle:@"取消" image:nil target:self action:@selector(rightButtonEvent) isLeft:NO];
//        _deleteBtn.hidden = NO;
//        _isEditing = YES;
//    }
//}
//
//
-(void)onDeleteBtn{
    [UIUtils showHudFailWithTint:@"删除失败"];
    [self.praiseTab setEditing:NO animated:YES];
}



#pragma mark - tableview delegete;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    

    return _dataArray.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = _dataArray[indexPath.row];
    NSArray * imageArray = dic[@"cover_pic"];
    
    if (imageArray.count!=1) {
        
        
        UILabel * titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10, 55, WIDTH -20, 20)];
        titleLabel.text = dic[@"title"];
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.numberOfLines = 2;
        [titleLabel sizeToFit];
        
        CGFloat widthImage = (WIDTH -40)/3;
        UIImageView * image;
        if (imageArray.count==0) {
            
            image = [[UIImageView alloc]initWithFrame:CGRectMake(10,CGRectGetMaxY(titleLabel.frame)+10 ,10 ,1)];
        }else {
            
            for (int i = 0; i<imageArray.count; i++) {
                
                image = [[UIImageView alloc]initWithFrame:CGRectMake(10+widthImage*i+10*i, CGRectGetMaxY(titleLabel.frame)+10, widthImage, widthImage *0.6)];
                [image sd_setImageWithURL:ImageUrl(imageArray[i])];
                image.layer.cornerRadius = 3.f;
                image.layer.masksToBounds = YES;
                
            }
            
        }
        
        return CGRectGetMaxY(image.frame)+40;
        
    }else{
        
        return 140.0f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.f;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //左滑删除
    return UITableViewCellEditingStyleDelete;
    
}
//修改左滑删除按钮的title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
    
        NSDictionary * dic = _dataArray[indexPath.row];
        
        NSString * str = [NSString stringWithFormat:@"%ld",[dic[@"id"]  integerValue]];
        
            [self deledateLikeRequestForNewsId:str];
 
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary * dic = _dataArray[indexPath.row];
    
    NSArray * imageArray = dic[@"cover_pic"];
    
    if (imageArray.count!=1) {
        
        static NSString * cellid = @"cellNews";
        
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        if (cell==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellid];
        }else {
            
            while ([cell.contentView.subviews lastObject] !=nil) {
                
                [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
            }
        }
        
        UILabel * likeTime  = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, WIDTH -20, 20)];
        likeTime.text = dic[@"create_time"];
        likeTime.textColor = UIColorFromRGB(0x999999);
        likeTime.font = [UIFont systemFontOfSize:14];
         [cell.contentView addSubview:likeTime];
        
        UIImageView * likeImage = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH - 38, 9, 22, 22)];
        likeImage.image = ImageName(@"my_Fabulous_default");
         [cell.contentView addSubview:likeImage];
        
        UILabel * titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(10, 55, WIDTH -20, 20)];
        titleLabel.text = dic[@"title"];
        titleLabel.font = [UIFont systemFontOfSize:16];
        titleLabel.numberOfLines = 2;
        [titleLabel sizeToFit];
        
        [cell.contentView addSubview:titleLabel];
        CGFloat widthImage = (WIDTH -40)/3;
        UIImageView * image;
        
        
        
        if (imageArray.count==0) {
            
            image = [[UIImageView alloc]initWithFrame:CGRectMake(10,CGRectGetMaxY(titleLabel.frame)+10 ,10 ,1)];
        }else {
            
            for (int i = 0; i<imageArray.count; i++) {
                
                image = [[UIImageView alloc]initWithFrame:CGRectMake(10+widthImage*i+10*i, CGRectGetMaxY(titleLabel.frame)+10, widthImage, widthImage *0.6)];
                [image sd_setImageWithURL:ImageUrl(imageArray[i])];
                image.layer.cornerRadius = 3.f;
                image.layer.masksToBounds = YES;
                [cell.contentView addSubview:image];
            }
            
        }
        
      
        
        UILabel * comment = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(image.frame)+10, 50, 18)];
        comment.font = [UIFont systemFontOfSize:13];
        comment.text= [NSString stringWithFormat:@"%@  %ld评",dic[@"create_time"],[dic[@"comment_num"] integerValue]];
        
        comment.textColor  = UIColorFromRGB(0x999999); ;
        comment .numberOfLines = 1;
        [comment sizeToFit];
        
        [cell.contentView addSubview:comment];
        
        return cell;
        
        
    }else {  // 单图
        
        LikeOneImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LikeOneImageTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [cell.nwsImage sd_setImageWithURL:ImageUrl(dic[@"cover_pic"][0])];
        
        if (ISP5||ISP4) {
            cell.nwsImage.frame = CGRectMake(10, 40+(100 -((WIDTH -40)/3 * 0.7))/2, (WIDTH -40)/3, (WIDTH -40)/3 * 0.7);
        }else {
            cell.nwsImage.frame = CGRectMake(10, 40+(100 -((WIDTH -40)/3 * 0.6))/2, (WIDTH -40)/3, (WIDTH -40)/3 * 0.6);
        }
        cell.nwsImage.layer.cornerRadius = 3.f;
        cell.nwsImage.layer.masksToBounds = YES;
        cell.nwsTime.frame = CGRectMake((WIDTH -40)/3 +20, 109, WIDTH - ((WIDTH -40)/3 +30), 20);
        cell.nwsTime.text = [NSString stringWithFormat:@"%@  %ld评",dic[@"create_time"],[dic[@"comment_num"] integerValue]];
        
        if (ISP5||ISP4) {
            cell.titleLabel.frame = CGRectMake((WIDTH -40)/3 +20, 55, WIDTH -((WIDTH -40)/3-5)-20, 20);
        }else{
            cell.titleLabel.frame = CGRectMake((WIDTH -40)/3 +20, 53, WIDTH -((WIDTH -40)/3-5)-20, 20);
        }
        cell.titleLabel.text  = dic[@"title"];
        cell.titleLabel.numberOfLines = 2;
        [cell.titleLabel sizeToFit];
        cell.likeTime.text = dic[@"create_time"];
        
        return cell;
        
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = _dataArray[indexPath.row];
    
    if ([dic[@"type"] intValue]==1) {
        
        NSLog(@"新闻");
        NewsDetailsViewController * homeDetiel = [[NewsDetailsViewController alloc]init];
        homeDetiel.news_idStr = [NSString stringWithFormat:@"%ld",[dic[@"news_id"] integerValue]];
        //        homeDetiel.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:homeDetiel animated:YES];
    }else {
        NSLog(@"随手拍");

        [self getActDetailsRequestForid:[NSString stringWithFormat:@"%ld",[dic[@"news_id"] integerValue]]];
    
    }
    
}

-(void)getLikeListRequest{
    
    NSDictionary * dic = @{
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId]
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_myLikeList_api) andparameters:dic Success:^(id responseObject) {
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            
            _dataArray =  responseObject;
            [_praiseTab reloadData];
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"msg"]);
        }
        
        [_praiseTab.mj_header endRefreshing];
        
        NSLog(@"responseObject = %@",responseObject);
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        [_praiseTab.mj_header endRefreshing];

        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
}

-(void)deledateLikeRequestForNewsId:(NSString *)ids{
    
    NSString * idsStr= [NSString stringWithFormat:@"{\"ids\":[%@]}",ids];
    
    NSLog(@"idsStr = %@",idsStr);
    NSDictionary * dic = @{
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"batch":idsStr
                           };
    
    NSLog(@"dic = %@",dic);
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(deledate_like_api) andparameters:dic Success:^(id responseObject) {
        
        [self getLikeListRequest];
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
}

-(void)getActDetailsRequestForid:(NSString *)newsId{
    
    NSDictionary * dic = @{@"news_id":newsId,
                           @"user_id":USER_DEFAULTGet(@"user_id")
                           };
    
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(activity_details_api) andparameters:dic Success:^(id responseObject) {
        
        NSDictionary *  dataDic = responseObject;
        NSLog(@"responseObject = %@",responseObject);
        
        
        
        NSLog(@"responseObject = %@",responseObject);
        
        USER_DEFAULTSet(dataDic[@"pic_url"], @"actDetailsIamgeArray");
        USER_DEFAULTSet(dataDic[@"is_fabulous"], @"act_is_fabulous");
        
        
        if ([dataDic[@"pic_url"] isKindOfClass:[NSArray class]]) {
            NSArray * array = dataDic[@"pic_url"];
            if (array.count==0) {
                
                USER_DEFAULTSet(@"http://a1.qpic.cn/psb?/V147v55d35m6eX/xXdZ2De4s1iE5gYJaikuWyqltDsmFf*LHHZ1ANFPtso!/m/dDABAAAAAAAA&bo=eAB4AAAAAAADByI!&rf=photolist", @"shareImage");
            }else {
                
                USER_DEFAULTSet(dataDic[@"pic_url"][0], @"shareImage");
            }
        }
        NSString * newsId= [NSString stringWithFormat:@"%ld",[dataDic[@"id"] integerValue]];
        USER_DEFAULTSet(newsId,@"shareNewsId");
        USER_DEFAULTSet(@"2",@"shareType");
        USER_DEFAULTSet(dataDic[@"title"], @"shareTitle");
        USER_DEFAULTSet(dataDic[@"content"], @"shareContent");
        USER_DEFAULTSet(dataDic[@"share_url"], @"shareUrl");
        
        
        ActiveDetailViewController * activeDetail = [[ActiveDetailViewController alloc]init];
        activeDetail.actIdStr = newsId;
        activeDetail.dataDic = dataDic;
        activeDetail.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:activeDetail animated:YES];
        
        
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else {
            SHuiMBhudTextNetError;
        }
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
